<template>
  <div class="information">
    <text-list label-width="200px" :column="1">
      <text-item label="账号名称：">{{ data.merchantName }}</text-item>
      <text-item label="账户类型：">{{ data.merchantTypeDict }}</text-item>
      <div class="business">
        <div class="">营业执照：</div>
        <div class="">{{ data.businessLicenseNumber }}</div>
        <div>
          <!-- <el-button type="primary" size="mini" @click="getImg">查看图片</el-button> -->
          <el-button type="primary" size="mini" @click="replaceBusiness">更换营业执照</el-button>
        </div>
      </div>
      <text-item label="注册金额：">{{ data.registeredFund }}</text-item>
      <div class="business">
        <div class="">联系手机：</div>
        <div class="">{{ data.phone }}</div>
        <div v-if="cancelAudit != 1">
          <el-button type="primary" size="mini" @click="getPhone">更换手机</el-button>
        </div>
        <div style="margin-left: 12px" v-if="cancelAudit != 1">
          <el-button type="primary" size="mini" @click="getDisable">{{
            statusText
          }}</el-button>
        </div>
        <div v-if="cancelAudit != 1">
          <el-button type="primary" size="mini" style="margin-left: 12px" @click="resetPasswordClick">重置密码</el-button>
        </div>
      </div>
      <text-item label="联系邮箱：">{{ data.email }}</text-item>
      <text-item label="联系地址：">{{ data.address }}</text-item>
      <text-item label="账户地址：">{{ data.accountAddress }}</text-item>
      <text-item label="商户入驻合同确认书：">
        <el-upload class="upload-demo" :action="action" :on-preview="handlePreview" :on-remove="handleRemove"
          :before-remove="beforeRemove" multiple :limit="1" :on-exceed="handleExceed" :file-list="fileList"
          :on-success="handleUploadSuccess">
          <el-button size="small" type="primary">点击上传</el-button>
          <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
        </el-upload>
      </text-item>
      <!-- <div class="business">
        <div class="">进件资料：</div>
        <div>
          <el-button type="primary" size="mini" @click="goInto">点击查看</el-button>
        </div>
      </div> -->
      <div class="business">
        <div class="">海易信企业信用报告：</div>
        <div>
          <div class="hyx_box">
            <span v-if="data.upCreditFileUrl == ''">暂无报告</span>
            <div v-if="data.upCreditFileUrl != ''">
              <el-button type="warning" size="mini" @click="reportPreview">报告预览</el-button>
              <el-button type="primary" size="mini" :loading="downloadLoading" @click="reportDownload">报告下载</el-button>
            </div>
          </div>
          <div v-if="data.upCreditFileUrl != ''">报告日期：{{ data.upCreditFileDate }}<span
              style="color: #999;font-size: 13px">（于{{ data.upCreditDate }}上传）</span></div>
        </div>
      </div>
      <div class="merchant_info">
        <p class="merchant_info_title">商家资料信息</p>
        <text-item label="营业执照：">
          <el-image class="el_img" :src="imgInfo.businessLicenseImg" :preview-src-list="[imgInfo.businessLicenseImg]">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
              <span>暂无图片</span>
            </div>
          </el-image>
        </text-item>
        <text-item label="经营者/法人身份信息：">
          <div style="display: flex;">
            <div class="lable_box">
              <el-image class="el_img" :src="imgInfo.manageIdCardFront" :preview-src-list="IdCardImgLs">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                  <span>暂无图片</span>
                </div>
              </el-image>
              <el-upload class="avatar-uploader" :action="imgAction" :show-file-list="false"
                :on-success="getManageIdCardFront" :before-upload="beforeAvatarUpload">
                <span style="margin-right: 10px;">身份证正面</span>
                <el-button size="mini" type="primary" :loading="loadingFront">修改</el-button>
              </el-upload>
            </div>
            <div class="lable_box">
              <el-image class="el_img" :src="imgInfo.manageIdCardBack" :preview-src-list="IdCardImgLs">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                  <span>暂无图片</span>
                </div>
              </el-image>
              <el-upload class="avatar-uploader" :action="imgAction" :show-file-list="false"
                :on-success="getManageIdCardBack" :before-upload="beforeAvatarUpload">
                <span style="margin-right: 10px;">身份证反面</span>
                <el-button size="mini" type="primary" :loading="loadingBack">修改</el-button>
              </el-upload>
            </div>
          </div>
        </text-item>
        <text-item label="结算信息：">
          <div style="display: flex;margin-bottom: 20px;">
            <span v-if="previewSrcList.length == 0">无</span>
            <el-image class="el_img" :src="item" v-for="(item, iIndex) in previewSrcList" :key="iIndex"
              :preview-src-list="previewSrcList">
            </el-image>
          </div>
        </text-item>
        <text-item label="其他资质：">
          <ImageUploadMore :limit="6" :fileSize="20" :previewType="'2'" :isShowTip="false" @successImg="getPictureList"
            :value="imgInfo.merchantQualificationImgList">
          </ImageUploadMore>
        </text-item>
      </div>
    </text-list>
    <div class="back" style="margin-top: 20px">
      <el-button size="medium" type="danger" style="margin-right: 30px" @click="rejectClick" v-if="data.status == 3">拒绝
      </el-button>
      <el-button size="medium" @click="back">返回</el-button>
    </div>
    <pahone-dialog v-if="phoneDialog" :id="id" :visible.sync="phoneDialog" @success="_handleSuccess" />
    <detail-dialog v-if="detailDialog" :id="data.id" :visible.sync="detailDialog" @success="_handleSuccess" />
    <img-detail-dialog v-if="ImgDetailDialog" :id="id" :imgUrl="data.businessLicenseImg"
      :visible.sync="ImgDetailDialog" />
    <!-- 更换营业执照 -->
    <BusinessDialog ref="dialogRef" @success="_handleSuccess"></BusinessDialog>
  </div>
</template>
<script>
// components
import Loading from "@/components/Loading/index";
import detailDialog from "./information/detailDialog";
import pahoneDialog from "./information/pahoneDialog";
import ImgDetailDialog from "./information/imgDetailDialog";
import BusinessDialog from "./replacingBusiness/index";
// api
import {
  getMerchantBaseInfoDetail,
  setMerchantStatus,
  merchantEnterFile,
  resetPassword,
  merchantImg,
  merchantImgRenew,
} from "@/api/merchants";
import {
  reject
} from "@/api/regitserVerify";
export default {
  components: {
    Loading,
    detailDialog,
    pahoneDialog,
    ImgDetailDialog,
    BusinessDialog,
  },
  props: {
    id: String,
  },
  inject: ["cancelAudit"],
  data() {
    return {
      detailDialog: false,
      ImgDetailDialog: false,
      phoneDialog: false,
      data: {},
      statusText: "禁用账户",
      enterFileUrl: '', //合同确认书url
      action: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile",
      httpImg: this.$IMG_URL + "/",
      fileList: [],
      downloadLoading: false,//下载loading
      imgInfo: { //图片信息
        licence: '',//开户许可证
        manageIdCardBack: '',//经营者身份证背面
        manageIdCardFront: '',//经营者身份证正面
        merchantQualificationImgList: [],//其他资质图片数组
        nfrSettleBankImg: '',//nfr结算银行图片正面
        nfrSettleBankImgBack: '',//nfr结算银行图片背面
        merchantId: '',//商家id
      },
      previewSrcList: [],//结算信息图片数组
      imgAction: process.env.VUE_APP_BASE_API + "/common/v1/upload",
      IdCardImgLs: [],//身份证图片数组
      loadingFront: false,
      loadingBack: false,
    };
  },
  computed: {},
  created() {
    this.getApi()
    // this.getDetail();
    // this.getMerchantImg()
  },
  methods: {
    getApi() {
      this.getDetail();
      this.getMerchantImg()
    },
    //更换营业执照
    replaceBusiness() {
      this.$refs.dialogRef.open(this.id);
    },
    //查询商家图片信息
    getMerchantImg() {
      merchantImg(this.id).then((res) => {
        this.imgInfo = res.result
        if (res.result.manageIdCardFront != '' && res.result.manageIdCardBack != '') {
          this.IdCardImgLs = [res.result.manageIdCardFront, res.result.manageIdCardBack] //身份图片信息预览大图数组
        }
        this.previewSrcList = [] //结算信息图片预览大图数组
        if (res.result.licence != '') {
          this.previewSrcList.push(res.result.licence)
        }
        if (res.result.nfrSettleBankImg != '') {
          this.previewSrcList.push(res.result.nfrSettleBankImg)
        }
        if (res.result.nfrSettleBankImgBack != '') {
          this.previewSrcList.push(res.result.nfrSettleBankImgBack)
        }
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.enterFileUrl = ''
    },
    handlePreview(file) { //点击文件
      // console.log(file);
      // window.location.href = file.url
      window.open(file.url)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleUploadSuccess(res) {
      this.enterFileUrl = res.result.url
      var params = {
        id: this.id,
        enterFileUrl: this.enterFileUrl,
      };
      merchantEnterFile(params).then((res) => {
        this.handleSuccess("操作成功");
        this.getDetail();
      });
    },
    //禁用账号
    getDisable() {
      var confirmButtonText = "禁用";
      var status = "";
      console.log("this.data.status", this.data.status);
      if (this.data.status == "1") {
        confirmButtonText = "禁用";
        status = "2";
      } else {
        confirmButtonText = "启用";
        status = "1";
      }
      this.$confirm(`确定要${confirmButtonText}该用户?`, "提示", {
        confirmButtonText: confirmButtonText,
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("id", this.id);
          var params = {
            id: this.id,
            status: status,
          };
          console.log(params, this.id);
          setMerchantStatus(params).then((res) => {
            this.handleSuccess(confirmButtonText + "成功");
            this.getDetail();
          });
        })
        .catch();
    },
    // 重置密码
    resetPasswordClick() {
      this.$confirm('是否重置登录密码为：mlm123456', '重置密码', {
        confirmButtonText: '重置密码',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = {
          id: this.id
        }
        resetPassword(params).then((res) => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.getDetail();
        });

      }).catch(() => { });
    },
    //获取基本信息
    getDetail() {
      getMerchantBaseInfoDetail(this.id).then((res) => {
        const {
          result
        } = res;

        this.statusText = result.status == 1 ? "禁用账户" : "启用账户";
        this.data = result;
        if (result.enterFile != '') {
          this.fileList = [{
            name: '合同确认书',
            url: result.enterFile
          }]
        }
      });
    },
    //更换手机号
    getPhone() {
      this.phoneDialog = true;
    },
    _handleSuccess() {
      this.getApi();
    },
    //查看照片
    getImg() {
      console.log("查看照片");
      this.ImgDetailDialog = true;
    },
    jumpzz() {
      //更换资金账户
      this.$router.push({
        path: "/moneyManagement/moneyAccount-list",
      });
    },
    //进件资料
    goInto() {
      //  this.$router.push({
      //     path: "/merchants/incoming-detail",
      //     query: {
      //       merchantId: this.data.id,
      //       pathType: 'merchantsDetail',
      //     },
      //   });
      this.detailDialog = true

    },
    //返回
    back() {
      this.$router.go(-1);
    },
    handleSuccess(msg) {
      if (msg === "已拒绝") {
        var type = "error";
      } else {
        var type = "success";
      }
      this.$message({
        message: msg,
        type: type,
        duration: 1500,
        onClose: () => {
          this.handleClose();
          this.$emit("success");
        },
      });
    },
    rejectClick() {
      //拒绝审核
      this.$confirm("是否拒绝?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "返回",
        type: "warning",
      })
        .then(() => {
          console.log("hgahah");
          reject(this.id).then((res) => {
            this.$message({
              message: "已拒绝【" + this.data.merchantName + "】入驻申请",
              type: "error",
              duration: 1500,
            });
            this.getDetail();
          });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        });
    },
    reportPreview() { //报告预览
      window.open(this.data.upCreditFileUrl)
    },
    reportDownload() { //报告下载
      const that = this
      that.downloadLoading = true
      var oReq = new XMLHttpRequest()
      var URL = this.data.upCreditFileUrl
      oReq.open('GET', URL, true)
      oReq.responseType = 'blob'
      oReq.onload = function (res) {
        var file = new Blob([oReq.response], {
          type: 'blob'
        })
        const a = document.createElement("a");
        const URL = window.URL || window.webkitURL;
        const herf = URL.createObjectURL(file);
        a.href = herf;
        a.download = '海易信企业信用报告.pdf'
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(herf);
        that.downloadLoading = false
      }
      oReq.send()
      setTimeout(() => {
        that.downloadLoading = false
      }, 2000)
    },
    //获取身份证正面
    getManageIdCardFront(res, file) {
      this.loadingFront = true
      this.imgInfo.manageIdCardFront = res.result.url
      this.uploadMerchantImgRenew()
    },
    //获取身份证反面
    getManageIdCardBack(res, file) {
      this.loadingBack = true
      this.imgInfo.manageIdCardBack = res.result.url
      this.uploadMerchantImgRenew()
    },
    //经营者/法人身份信息上传前判断
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt20M = file.size / 1024 / 1024 < 20;

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 jpg/png 格式!');
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!');
        return false
      }
      // return isJPG && isLt2M;
    },
    //获取资质图片
    getPictureList(e) {
      if (e != '') {
        this.imgInfo.merchantQualificationImgList = e.split(",")
      } else {
        this.imgInfo.merchantQualificationImgList = []
      }
      this.uploadMerchantImgRenew()
    },
    //更新图片信息
    uploadMerchantImgRenew() {
      this.imgInfo.merchantId = this.id
      var data = {
        ...this.imgInfo,
      }
      merchantImgRenew(data).then((res) => {
        this.$message({
          type: 'success',
          message: '操作成功'
        });
        this.getApi();
        this.loadingFront = false
        this.loadingBack = false
      }).catch(() => {
        this.loadingFront = false
        this.loadingBack = false
        setTimeout(() => {
          this.getApi();
        }, 1000)
      })
    },
  },
};

</script>
<style lang="scss" scoped>
@import "../../style/merchantsDetail";

::v-deep.information .el-upload-list {
  width: 400px;
}

.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
  }

  .main {
    margin: 0 auto;
  }

  .pic-list {
    display: flex;
    justify-content: space-around;
    width: 660px;
  }

  .img {
    display: block;
    width: 200px;
    height: auto;
  }
}

.button_box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.merchant_info_title {
  width: 170px;
  text-align: right;
  font-size: 16px;
  font-weight: bold;
  margin: 10px 0;
  color: #333333;
}

.lable_box {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 8px;
  font-size: 14px;
  margin-bottom: 10px;
}

.el_img {
  width: 146px;
  height: 146px;
  margin-right: 8px;
  border: 1px solid #c0ccda;
  border-radius: 6px;
}

::v-deep .image-slot {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
